/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from "antd";
import { getScopeList, scopeDelete, scopeFreeze, scopeAdd } from "@/services/scope";
import { isArray } from "@/utils/utils";

export default {
  namespace: "scope",

  state: {
    list: null,
    currentIndex: 0,
  },

  effects: {
    *scopeAdd({ payload, then }, { put, call }) {
      const response = yield call(scopeAdd, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success("已保存");
      } else {
        message.error(msg);
      }
      if (then) {
        then(response);
      }
    },
    *scopeFreeze({ payload, then }, { put, call }) {
      const response = yield call(scopeFreeze, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(payload.status == 1 ? "已开启" : "已冻结");
      } else {
        message.error(msg);
      }
      if (then) {
        then(response);
      }
    },
    *scopeDelete({ payload, then }, { put, call }) {
      const response = yield call(scopeDelete, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success("已删除");
      } else {
        message.error(msg);
      }
      if (then) {
        then(response);
      }
    },
    *getScopeList({ payload, __dva_resolve, force }, { put, call, select }) {
      const { list } = yield select(_ => _.scope);
      if (!force && list && list.length > 0) {
        __dva_resolve(list);
        return;
      }
      const response = yield call(getScopeList, payload);
      if (!response) return;
      const { code, data } = response;
      if (code == 0 && isArray(data)) {
        yield put({
          type: "saveScopeList",
          payload: {
            list: data,
          },
        });
        __dva_resolve(data);
      }
    },
  },

  reducers: {
    saveScopeList(state, { payload }) {
      return {
        ...state,
        list: payload.list,
      };
    },
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
